<?php


namespace app\common\model;


use think\Db;

class Coupon extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_coupon';
    // 主键ID
    protected $pk = 'coupon_id';

    /**
     * @param array $where  // 查询的条件
     * @param string $item  // 查询的参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getOne($where=[1], $item='*',$isArray = false)
    {
        $rs = $this
            ->field($item)
            ->where($where)
            ->find();
        if($isArray){
            $rs = $rs->toArray();
        }
        return $rs;
    }

    // h5获取消费券列表
    function get_coupon_list($userid,$limit){
        $where = [
            ["c.status",'=',1],
            ["c.is_del",'=',1],
        ];
        $field = [
            'c.*',
            'case when (select count(*) from ddt_coupon_receive cr where cr.coupon_id = c.coupon_id and user_id = '.$userid.' and cr.is_use in (1,2))>0 then 1 else 0 end as is_get'
        ];
        $data = $this
            ->alias('c')
            ->field($field)
            ->where($where)
            ->paginate($limit);

//        echo $this->getLastSql();die;
        return $data;
    }

    // 获取分页列表
    function get_list_page($cond,$orderby,$item,$limit)
    {
        $where = null;
        if(!empty($cond['group_name'])){
            $where[] = ['group_name','like',"%".$cond['group_name']."%"];
        }
        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);

        return $rs;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ['coupon_id' => $id];
            $params['update_time'] = time();
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            $params['add_time'] = time();
            // 更新数据
            $this->allowField(true)->save($params);
            $rs = $this->coupon_id;
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

    // 单独编辑
    function edit2($params, $where){
        $rs = $this->allowField(true)->save($params, $where);
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

    // 消费券减数量
    function decsum($where){
        $rs = $this
            ->where($where)
            ->setDec('coupon_number', 1);
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }
}